package com.bifrost.repository;

import com.bifrost.entity.Product;
import com.bifrost.entity.ProductSku;
import com.bifrost.entity.Promotion;
import com.bifrost.entity.PromotionSku;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author rangf
 * @date 2018/3/7
 */
public interface PromotionSkuRepository extends JpaRepository<PromotionSku, Long> , JpaSpecificationExecutor<PromotionSku> {

    /**
     * 获取促销活动可用库存
     *
     * @param promotionId
     * @return
     */
    @Query(value = "SELECT SUM(P.INVENTORY_AVAILABLE) FROM `PROMOTION_SKU` P WHERE P.PROMOTION_ID = ?1 AND P.PRODUCT_ID= ?2", nativeQuery = true)
    Integer sumStockAviliable(Long promotionId, Long productId);

    /**
     * 获取促销活动总库存
     *
     * @param promotionId
     * @return
     */
    @Query(value = "SELECT SUM(P.INVENTORY) FROM `PROMOTION_SKU` P WHERE P.PROMOTION_ID = ?1 AND P.PRODUCT_ID= ?2", nativeQuery = true)
    Integer sumStock(Long promotionId, Long productId);

    /**
     *
     * @param promotion
     * @param sku
     * @return
     */
    PromotionSku findFirstByPromotionAndProductSku(Promotion promotion, ProductSku sku);

    @Modifying
    @Transactional
    @Query(value = "UPDATE PROMOTION_SKU SET INVENTORY_AVAILABLE=INVENTORY_AVAILABLE + ?2 WHERE ID = ?1", nativeQuery = true)
    int incrementInventory(Long promotionSkuId, Integer quantity);

    @Modifying
    @Transactional
    @Query(value = "UPDATE PROMOTION_SKU SET INVENTORY_AVAILABLE=INVENTORY_AVAILABLE - ?2 WHERE ID = ?1 AND INVENTORY_AVAILABLE >= ?2", nativeQuery = true)
    int decrementInventory(Long promotionSkuId, Integer quantity);

    List<PromotionSku> findAllByPromotion(Promotion promotion);

    List<PromotionSku> findAllByPromotionAndProduct(Promotion promotion, Product product);


}
